import React, { useState, useEffect } from 'react'
import { AppProps } from 'next/app'
import '../styles/global.css'
import { createMuiTheme, ThemeProvider } from '@material-ui/core/styles';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import { makeStyles } from '@material-ui/core/styles';
export type ThemeTypes = 'light' | 'dark'

const useStyles = makeStyles(({ breakpoints, spacing, palette }) => ({
  loading: {
    opacity: '0 !important',
    pointerEvents: 'none',
    zIndex: 0
  }
}))

if (typeof window !== 'undefined') {
  window.setTheme = function (theme) {
    const event = new Event('$themeChange')
    localStorage.setItem('themeType', theme)
    window.dispatchEvent(event)
  }
}

export default function App({ Component, pageProps }: AppProps) {
  const classes = useStyles()
  const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
  const [themeType, setThemeType] = useState(prefersDarkMode ? 'dark' : 'light')
  useEffect(() => {
    function onThemeChange() {
      setThemeType(localStorage?.getItem?.('themeType') as ThemeTypes)
    }
    window.addEventListener('$themeChange', onThemeChange)
    return function () {
      window.removeEventListener('$themeChange', onThemeChange)
    }
  }, [])

  const theme = React.useMemo(
    () =>
      createMuiTheme({
        palette: {
          type: themeType as ThemeTypes,
        },
      }),
    [themeType],
  );
  return <ThemeProvider theme={theme}>
    <div
      className={classes.loading}
      style={{ background: '#fff', height: '100vh', width: '100vw', left: 0, top: 0, position: 'fixed', opacity: 1, zIndex: 999, transition: '0.5s' }}
    />
    <Component {...pageProps} />
  </ThemeProvider>
}
